package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.jwt.JsonUtils;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.redis.RedisUtils;
import com.hmdp.service.IShopService;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.StringTools;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.constants.RedisConstants.*;


/**
 * @author luojun
 * @desc ShopServiceImpl
 * @date 2025/04/28
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final ExecutorService CACHE_BUILDER_EXECUTOR = Executors.newFixedThreadPool(10);

    @Override
    public Result queryShopById(Long id) {
        Shop shop = queryShopWithLogicalExpire(id);
        if (null == shop){
            return Result.fail("店铺信息不存在");
        }
        //CacheClient.queryWithPassThrough(CACHE_SHOP,id,Shop.class,this::getById,10L,TimeUnit.SECONDS);
        return Result.ok(shop);
    }

    /**
     * 基于互斥锁解决缓存击穿问题
     */
    public Result queryShopWithMutex(Long id) {
        String key = CACHE_SHOP + id;
        Shop shopJson = (Shop) redisUtils.get(key, Shop.class);
        //缓存命中返回shop
        if (null != shopJson) {
            return Result.ok(shopJson);
        }
        //缓存命中但value为空
        if (redisUtils.exists(key)) {
            return Result.fail("店铺信息不存在");
        }
        String lockKey = null;
        Shop shop = null;
        try {
            //获取锁
            lockKey = LOCK_SHOP + id;
            if (!tryLock(lockKey)) {
                Thread.sleep(50);
                return queryShopWithMutex(id);
            }

            shop = getById(id);
            //模拟重建
            Thread.sleep(200);
            if (null == shop) {
                redisUtils.setex(key, null, CACHE_NULL_TTL);
                return Result.fail("店铺不存在!");
            }
            redisUtils.setex(key, shop, CACHE_SHOP_TTL);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            unLock(lockKey);
        }

        return Result.ok(shop);
    }

    private boolean tryLock(String key) {
        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(aBoolean);
    }

    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }

    @Override
    @Transactional
    public Result update(Shop shop) {
        Long id = shop.getId();
        if (null == id) {
            return Result.fail("店铺id不能为空");
        }
        //先更新数据库再删缓存
        updateById(shop);
        redisUtils.delete(CACHE_SHOP + shop.getId());
        return Result.ok();
    }

    /**
     * 使用stringRedisTemplate做法
     *
     * @param id
     * @return
     */
    public Shop queryShopById4Json(Long id) {
        String key = CACHE_SHOP + id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        if (!StringTools.isEmpty(shopJson)) {
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
        Shop shop = getById(id);
        return shop;
    }

    //互斥锁解决缓存击穿
    public Result queryShopWithMutualExclusion(Long id) {
        String key = CACHE_SHOP + id;
        Shop shop = (Shop) redisUtils.getx(key);
        if (shop != null) {
            return Result.ok(shop);
        }
        if (redisUtils.exists(key)) {
            return Result.fail("店铺不存在");
        }
        Shop shop1 = null;
        try {
            //尝试获取互斥锁
            boolean flag = redisUtils.setnx(LOCK_SHOP + id, 1, 10);
            //获取锁失败
            if (!flag) {
                Thread.sleep(50);
                queryShopWithMutualExclusion(id);
            }

            // 4. 再次检查缓存（双重检测，防止重复重建）
            shop = (Shop) redisUtils.getx(key);
            if (shop != null) {
                return Result.ok(shop);
            }

            shop1 = getById(id);
            if (null == shop1) {
                redisUtils.setex(key, null, CACHE_NULL_TTL);
            }
            redisUtils.setex(key, shop1, CACHE_SHOP_TTL);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            redisUtils.delete(LOCK_SHOP + id);
        }
        return Result.ok(shop1);
    }

    //逻辑过期解决缓存击穿问题1
    public Shop queryShopWithLogicalExpire(Long id) {
        String key = CACHE_SHOP + id;
        Object shopJson = redisUtils.getx(key);

        RedisData redisData = JSONUtil.toBean(JSONUtil.parseObj(shopJson),RedisData.class);
        JSONObject jsonObject = (JSONObject) redisData.getData();

        Shop shop = JSONUtil.toBean(jsonObject, Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        if (null == redisData || null == redisData.getData()) {
            return null;
        }
        //5 判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            //5.1未过期，返回旧数据
            return shop;
        }
        //5.2 已过期，缓存重建，尝试获取互斥锁
        boolean flag = redisUtils.setnx(LOCK_SHOP + id, 1, 10);
        if (flag) {
            //获取互斥锁成功，开启独立线程，实现缓存重建
            CACHE_BUILDER_EXECUTOR.submit(() -> {
                try {
                    saveShop2Redis(id, 20L);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    //释放锁
                    redisUtils.delete(LOCK_SHOP + id);
                }
            });
        }
        return shop;
    }

    public void saveShop2Redis(Long id, Long expireSeconds) throws InterruptedException {
        Thread.sleep(200);
        Shop shop = getById(id);
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        //return Result.ok(redisData);
        redisUtils.set(CACHE_SHOP + id, redisData);
    }


    public Result queryShopWithPassThrough(Long id) {
        String key = CACHE_SHOP + id;
        Shop shopJson = (Shop) redisUtils.get(key, Shop.class);
        //缓存命中返回shop
        if (null != shopJson) {
            return Result.ok(shopJson);
        }
        //缓存命中但value为空
        if (redisUtils.exists(key)) {
            return Result.fail("店铺信息不存在");
        }
        Shop shop = getById(id);
        if (null == shop) {
            redisUtils.setex(key, null, CACHE_NULL_TTL);
            return Result.fail("店铺不存在!");
        }
        redisUtils.setex(key, shop, CACHE_SHOP_TTL);
        return Result.ok(shop);
    }

    /**
     * 缓存穿透改进方案：缓存空对象
     *
     * @param id
     * @return
     */
    public Result queryShopWithPassThroughMethod1(Long id) {
        String key = CACHE_SHOP + id;
        Shop shopJson = (Shop) redisUtils.getx(key);
        if (null != shopJson) {
            return Result.ok(shopJson);
        }
        if (redisUtils.exists(key)) {
            return Result.fail("店铺不存在!");
        }
        //查数据库
        Shop shop = getById(id);
        //存redis
        if (null == shop) {
            redisUtils.setex(key, null, CACHE_NULL_TTL);
            return Result.fail("店铺不存在!");
        }
        redisUtils.setex(key, shop, CACHE_SHOP_TTL);
        return Result.ok(shop);
    }

    /**
     * 缓存雪崩方案一：给不同的key添加随机值
     *
     * @param id
     * @return
     */
    public Result queryShopWithCacheAvalancheMethod1(Long id) {
        String key = CACHE_SHOP + id;
        Shop shopJson = (Shop) redisUtils.getx(key);
        if (null != shopJson) {
            return Result.ok(shopJson);
        }
        if (redisUtils.exists(key)) {
            return Result.fail("店铺不存在!");
        }
        //查数据库
        Shop shop = getById(id);
        //存redis
        if (null == shop) {
            redisUtils.setex(key, null, CACHE_NULL_TTL);
            return Result.fail("店铺不存在!");
        }
        //生成[0,n)之间的随机数
        redisUtils.setex(key, shop, CACHE_SHOP_TTL + new Random().nextInt(10));
        return Result.ok(shop);
    }
}
